import {Card, Button, Tabs, Table, Space, Tag, Modal, Form, Input, Select, Radio, message} from "antd";
import './Financial.less';
import Bank from '../../components/financial/Bank';
import {useEffect, useState} from "react";
import http from "../../utils/http";

const Financial = () => {
    const { TabPane } = Tabs;
    const { Option } = Select;
    const [form] = Form.useForm();

    let [visible,changeVisible] = useState(false);
    let [withdrawalVisible,changeWithdrawalVisible] = useState(false);
    let [withdrawalForm,setWithdrawalCard] = useState({
        withdrawalCard:'',
        withdrawalMoney:1000,
        withdrawalCustomMoney:''
    });
    //数据
    let [banks,setBanks] = useState([]);
    let [dataRecord,setDataRecord] = useState([{
        s: '1',
        withdrawalTime: '2019-6-19',
        money: 80.50,
        account: '6228481561589687751',
        status:'提现中',
        specify:'无'
    }]);
    let [dataBalance,setDataBalance] = useState([
        {
            id: '1',
            settlement_date: '2019-6-19',
            type: '订单分佣',
            amount: 1000,
            orderID: '5266325',
            instructions:'无'
        },
        {
            id: '2',
            settlement_date: '2019-6-26',
            type: '订单分佣',
            amount: 20000,
            orderID:'5266326',
            instructions:'无'
        },
    ]);
    let [dataDownloadRecord,setDataDownloadRecord] = useState([
        {
            id:1,
            dateTime: '2019-6-29 14:29:36',
            operator: 'admin',
            state:'成功',
            operation: '下载'
        },
        {
            id:2,
            dateTime: '2019-06-26  16:20:20',
            operator: 'admin',
            state:'失败',
            operation:"下载"
        },
    ]);
    let [amount,setAmount] = useState('0.00');
    let [withdrawalsMoney,setWithdrawalsMoney] = useState('0.00');

    const [formSize, setFormSize] = useState('default');

    useEffect(()=>{
        getWithdrawalRecList();
        getIncomeDetailList();
        getBanks();
        getAmount();
        getWithdrawalsMoney();
        getDownloadRecord();
    },[])

    const getWithdrawalRecList = () => {
        http({
            url:'api/financeController/withdrawalRecList',
            method:'post',
            data:{
                id:1
            }
        }).then((res)=>{
            res.data.forEach((v)=>{
                v.withdrawalTime = v.withdrawalTime.substring(0,10);
            })
            setDataRecord(res.data)
            // console.log(res.data)
        });
    }
    const getIncomeDetailList = () => {
        http({
            url:'api/financeController/incomeDetailList',
            method:'post',
            data:{
                id:1
            }
        }).then((res)=>{
            console.log('收支明细',res)
            if (res.code == 200){
                res.data.forEach((v)=>{
                    v.type = '订单佣金';
                    v.incomeTime = v.incomeTime.substring(0,10);
                })
            }else if(res.code == 500){
                message.error('收支明细--' + res.msg);
            }
            setDataBalance(res.data);
        }).catch(err=>{
            console.log(err);
        });
    }
    const getBanks = () => {
        http({
            url:'api/financeController/adminInformation',
            method:'post',
            data:{
                id:1
            }
        }).then((res)=>{
            setBanks(res.data);
            // console.log(res.data);
        });
    }
    const getAmount = () => {
        http({
            url:'api/financeController/withdrawalRecMoney',
            method:'post',
            data:{
                id:1
            }
        }).then((res)=>{
            setAmount(res.data.toFixed(2));
        })
    }
    const getWithdrawalsMoney = () => {
        http({
            url:'api/financeController/withdrawalsMoney',
            method:'post',
            data:{
                id:1
            }
        }).then(res=>{
            setWithdrawalsMoney(res.余额.s.toFixed(2))
            console.log(res)
        })
    }
    const getDownloadRecord = ()=>{
        http({
            url:'api/financeController/exportWordList',
            method:'post',
            data:{}
        }).then(res=>{
            res.data.forEach(v=>{
                let date = new Date(v.adminTime).getTime();
                v.adminTime = setTimeFormat(date);
            })
            setDataDownloadRecord(res.data);
            console.log('导出记录',res.data);
        }).catch(err=>{
            console.log(err)
        })
    }

    const add0 = (m)=>m<10?'0'+m:m;
    const setTimeFormat = (date)=>{
        let time = new Date(date);
        let y = time.getFullYear();
        let m = time.getMonth()+1;
        let d = time.getDate();
        let h = time.getHours();
        let mm = time.getMinutes();
        let s = time.getSeconds();
        return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
    }
    const openModal = ()=>{
        changeVisible(true)
    }
    const closeModal = ()=>{
        changeVisible(false)
    }
    const showWithdrawalModal = ()=>{
        changeWithdrawalVisible(true)
    }
    const hideModal = ()=>{
        setWithdrawalCard({
            withdrawalCard:'',
            withdrawalMoney:1000,
        });
        changeWithdrawalVisible(false)
    }
    //下载导出记录
    const reDownload = (url)=>{
        console.log("下载");
        window.location.href = url;
    }
    const expectOrder = ()=>{
        let exportData = {id:"1"};
        console.log(JSON.stringify(exportData))
        http({
            url:'api/financeMoneyController/exportMoney',
            method:'post',
            data:exportData,
            responseType: 'blob',//定义接口响应的格式,很重要
        }).then(res=>{
            console.log("res:",res);
            window.location.href = res.msg;
        }).catch(err=>{
            console.log(err);
        })
        // console.log('导出');
    }
    //提现功能
    const withdrawal = ()=>{
        if (withdrawalForm.withdrawalCard){
            let withdrawalMoney = withdrawalForm.withdrawalMoney;
            if(withdrawalForm.withdrawalCustomMoney != ''){
                withdrawalMoney = withdrawalForm.withdrawalCustomMoney;
            }
            console.log(withdrawalForm.withdrawalCard,withdrawalMoney);
            http({
                url:'api/financeController/withdrawals',
                method:'post',
                data:{
                    bankCard: withdrawalForm.withdrawalCard,
                    id: 1,
                    money: parseInt(withdrawalMoney)
                }
            }).then(res=>{
                setWithdrawalCard({
                    withdrawalCard:'',
                    withdrawalMoney:1000,
                    withdrawalCustomMoney:''
                });
                if (res.code == 200){
                    message.success(res.msg);
                }else {
                    message.warning(res.msg);
                }
                getAmount();
                console.log(res);
            }).catch(err=>{
                console.log(err);
            })
            changeWithdrawalVisible(false)
        }else {
            message.warning('未选择银行卡');
        }
    }

    const operations = <div>
                        <Button type={'link'} onClick={openModal}>导出记录</Button>
                        <Button type={'primary'} onClick={expectOrder.bind(this)}>订单导出</Button>
                    </div>;

    const columnsRecord = [
        {
            title: '序号',
            dataIndex: 's',
            key: 's',
            align:'center'
        },
        {
            title: '提现日期',
            dataIndex: 'withdrawalTime',
            key: 'withdrawalTime',
            align:'center'
        },
        {
            title: '提现金额',
            dataIndex: 'money',
            key: 'money',
            align:'center'
        },
        {
            title: '收款账户',
            dataIndex: 'account',
            key: 'account',
            align:'center'
        },
        {
            title: '提现状态',
            dataIndex: 'status',
            key: 'status',
            align:'center'
        },
        {
            title: '说明',
            dataIndex: 'specify',
            key: 'specify',
            align:'center'
        },
    ];
    const columnsBalance = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            align:'center'
        },
        {
            title: '结算日期',
            dataIndex: 'incomeTime',
            key: 'incomeTime',
            align:'center'
        },
        {
            title: '结算类型',
            dataIndex: 'type',
            key: 'type',
            align:'center'
        },
        {
            title: '结算金额',
            dataIndex: 'rake',
            key: 'rake',
            align:'center'
        },
        {
            title: '订单ID',
            dataIndex: 'oid',
            key: 'oid',
            align:'center'
        },
        {
            title: '说明',
            dataIndex: 'specif',
            key: 'specif',
            align:'center'
        },
    ];
    const columnsDownloadRecord = [
        {
            title: '日期',
            dataIndex: 'adminTime',
            key: 'adminTime',
            align:'center'
        },
        {
            title: '操作人员',
            dataIndex: 'operator',
            key: 'operator',
            align:'center'
        },
        {
            title: '状态',
            dataIndex: 'state',
            key: 'state',
            align:'center',
            render: (text,record) => (
                <Tag color={text?"green":"volcano"} key={record.id}>
                    {text?'成功':'失败'}
                </Tag>
            ),
        },
        {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            align:'center',
            render: (text, record) => {
                if(record.state){
                    return (
                        <Space size="middle">
                            <Button style={{color: 'red',fontSize:'12px'}} type={'link'}
                                    onClick={reDownload.bind(this, record.state)}>下载</Button>
                        </Space>
                    )
                }else{
                    return (
                        <Space size="middle"></Space>
                    )
                }
            },
        }
    ];

    const Banks = banks.map((v)=><Bank bank={v} bind={v.bind}/>);
    const BankOption = banks.map((v)=> {
        if(v.bind){
            return (
                <Option value={v.cardId}>
                <span style={{display: 'flex', justifyContent: 'space-between'}}>
                    <span>{v.cardId}</span>
                    <span>{v.bankAccount}</span>
                </span>
                </Option>)
        }
    });

    form.setFieldsValue(withdrawalForm);

    return (
        <div className='financial-mainBox'>
            <Card className='financial-mainCard'>
                <Card>
                    <div className='financial-topCard-top'>
                        <div style={{width:'40%'}}>
                            <div className='financial-money'>
                                <div style={{marginRight:'70px'}}>
                                    <div className='financial-moneyTitle'>账户总额</div>
                                    <div style={{lineHeight:'60px'}}><span className='financial-money-amount'>{amount}</span><span className='financial-money-unit'>元</span></div>
                                </div>
                                <div>
                                    <div className='financial-moneyTitle'>提现中</div>
                                    <div style={{lineHeight:'60px'}}><span className='financial-money-withdrawal'>{withdrawalsMoney}</span><span className='financial-money-unit'>元</span></div>
                                </div>
                            </div>
                            <div className='financial-topCard-bottom'>
                                <Button className='financial-withdrawal' type='primary' shape={'round'} onClick={showWithdrawalModal}>提现</Button>
                            </div>
                        </div>

                        <div className='financial-bank'>
                            <Bank/>
                            {Banks}
                        </div>
                    </div>
                </Card>
                <Tabs tabBarExtraContent={operations}>
                    <TabPane tab="提现记录" key="1">
                        <Table dataSource={dataRecord} columns={columnsRecord} pagination={{ position: ['none', 'none'] }} />
                    </TabPane>
                    <TabPane tab="收支明细" key="2">
                        <Table dataSource={dataBalance} columns={columnsBalance} pagination={{ position: ['none', 'none'] }} />
                    </TabPane>
                </Tabs>
            </Card>

            <div>
                <Modal className={'financial-modal'} title="导出记录" visible={visible} onCancel={closeModal} footer={null}>
                    <Table dataSource={dataDownloadRecord}
                           columns={columnsDownloadRecord}
                           pagination={{ position: ['none', 'none'] }}
                           className={'financial-modal-table-record'}
                    />
                </Modal>
                <Modal
                    className={'financial-withdrawal'}
                    title="提现"
                    visible={withdrawalVisible}
                    onOk={withdrawal}
                    onCancel={hideModal}
                    okText="提现"
                    cancelText="取消"
                >
                    <Form
                        labelCol={{
                            span: 4,
                        }}
                        wrapperCol={{
                            span: 16,
                        }}
                        layout="horizontal"
                        form={form}
                        initialValues={withdrawalForm}
                        size={formSize}
                    >
                        <Form.Item label="银行卡" name={'withdrawalCard'}>
                            <Select
                                placeholder={'请选择银行卡'}
                                value={withdrawalForm.withdrawalCard}
                                style={{width:'100%'}}
                                allowClear
                                onChange={val=>{withdrawalForm.withdrawalCard = val}}>
                                {BankOption}
                            </Select>
                        </Form.Item>
                        <Form.Item label="取款金额" name={'withdrawalMoney'}>
                            <Radio.Group
                                style={{display:'flex',justifyContent:'space-between'}}
                                value={withdrawalForm.withdrawalMoney}
                                defaultValue={1000}
                                buttonStyle="solid"
                                onChange={ev=>{withdrawalForm.withdrawalMoney = ev.target.value}}>
                                <Radio.Button value={1000}>1000元</Radio.Button>
                                <Radio.Button value={2000}>2000元</Radio.Button>
                                <Radio.Button value={5000}>5000元</Radio.Button>
                                <Radio.Button value={10000}>10000元</Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label="取款金额" name={'withdrawalCustomMoney'}>
                            <Input
                                placeholder={'自定义金额（最低10元）'}
                                value={withdrawalForm.withdrawalCustomMoney}
                                type={'number'}
                                onChange={ev=>{withdrawalForm.withdrawalCustomMoney = ev.target.value;}}/>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    );
}

export default Financial;